<template>
  <div>
    <header style="display: flex; margin-bottom: -0.5%">
      <h1>算法配置</h1>
    </header>
    <main
      style="
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      "
    >
      <div
        style="
          width: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-bottom: 20px;
        "
      >
        <a style="width: 140px; margin-left: 10px; font-size: 20px"
          >选择配置电路：</a
        >
        <el-select
          v-model="isSelect"
          placeholder="请选择要进行配置的电路"
          size="large"
          style="width: 60%"
        >
          <el-option
            v-for="item in result"
            :key="item"
            :label="item"
            :value="item"
            @click="getConfig(item)"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          size="large"
          style="background-color: #595959; margin-left: 2.5%"
          @click="reset"
          >重置
        </el-button>
      </div>
      <!-- 卡片-->
      <div style="width: 95%; display: flex; justify-content: center">
        <el-card
          style="
            width: 98%;
            justify-content: center;
            align-items: center;
            margin-top: -5px;
          "
        >
          <el-button
            type="primary"
            style="
              background-color: #003f82;
              margin-bottom: 10px;
              margin-left: 5%;
            "
            @click="uploadAlgorithm"
            >上传当前配置
          </el-button>
          <el-tag
            >修改'演算时间'、'单个变量维度划分网格数'、'单轮演算仿真次数'这三个字段不会删除之前保存在数据库内的计算结果。</el-tag
          >
          <div
            style="
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
            "
          >
            <!-- 表格-->
            <el-table
              stripe
              border
              max-height="560px"
              :data="tableData1"
              style="width: 90%; height: 100%"
            >
              <el-table-column type="index" label="序号" width="60">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="参数名称" width="360">
                <template #default="scope">
                  <div
                    @click.stop="editCell(scope.row, '参数名称')"
                    style="height: 100%; width: 100%"
                  >
                    <span @click.stop="editCell(scope.row, '参数名称')">{{
                      scope.row.参数名称
                    }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="基本默认键值" width="280">
                <template #default="scope">
                  <div
                    @click.stop="editCell(scope.row, '基本默认键值')"
                    style="height: 100%; width: 100%"
                  >
                    <el-input
                      v-if="scope.row.editingColumn === '基本默认键值'"
                      v-model="scope.row.基本默认键值"
                      @blur="saveEdit(scope.row)"
                      @focus="handleFocus(scope.$index)"
                    />
                    <span
                      v-else
                      @click.stop="editCell(scope.row, '基本默认键值')"
                      >{{ scope.row.基本默认键值 }}</span
                    >
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="最小值">
                <template #default="scope">
                  <div
                    @click.stop="editCell(scope.row, '最小值')"
                    style="height: 100%; width: 100%"
                  >
                    <el-input
                      v-if="scope.row.editingColumn === '最小值'"
                      v-model="scope.row.最小值"
                      @blur="saveEdit(scope.row)"
                      @focus="handleFocus(scope.$index)"
                    />
                    <span v-else @click.stop="editCell(scope.row, '最小值')">{{
                      scope.row.最小值
                    }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="最大值">
                <template #default="scope">
                  <div
                    @click.stop="editCell(scope.row, '最大值')"
                    style="height: 100%; width: 100%"
                  >
                    <el-input
                      v-if="scope.row.editingColumn === '最大值'"
                      v-model="scope.row.最大值"
                      @blur="saveEdit(scope.row)"
                      @focus="handleFocus(scope.$index)"
                    />
                    <span v-else @click.stop="editCell(scope.row, '最大值')">{{
                      scope.row.最大值
                    }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="默认值">
                <template #default="scope">
                  <div
                    @click.stop="editCell(scope.row, '默认值')"
                    style="height: 100%; width: 100%"
                  >
                    <el-input
                      v-if="scope.row.editingColumn === '默认值'"
                      v-model="scope.row.默认值"
                      @blur="saveEdit(scope.row)"
                      @focus="handleFocus(scope.$index)"
                    />
                    <span v-else @click.stop="editCell(scope.row, '默认值')">{{
                      scope.row.默认值
                    }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="分析步长值">
                <template #default="scope">
                  <div
                    @click.stop="editCell(scope.row, '分析步长值')"
                    style="height: 100%; width: 100%"
                  >
                    <el-input
                      v-if="scope.row.editingColumn === '分析步长值'"
                      v-model="scope.row.分析步长值"
                      @blur="saveEdit(scope.row)"
                      @focus="handleFocus(scope.$index)"
                    />
                    <span
                      v-else
                      @click.stop="editCell(scope.row, '分析步长值')"
                      >{{ scope.row.分析步长值 }}</span
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>
    </main>
  </div>
</template>
<script setup name="算法配置">
import {
  defineAsyncComponent,
  reactive,
  ref,
  onMounted,
  onUnmounted,
} from "vue";
import { ElMessage } from "element-plus";
import {
  addAlgorithm,
  addAlgorithmPre,
  getAlgorithm,
} from "@/server/algorithm";
import { circuitServer } from "@/server/iIndex";
import router from "@/router/index.js";

const isSelect = ref("");
const results = ref([]);
const result = ref([]);
const tableData = ref([]);
const resultData = ref({
  参数名称: [],
  最小值: [],
  最大值: [],
  默认值: [],
  分析步长值: [],
  基本默认键值: [],
});
const tableData1 = ref([]);

const reset = () => {
  router.go(0);
};

function preprocessValue(value) {
  value = value.replace(/(?<=\D|^)\./g, "0.");
  value = value.replace(/\.(?=\D|$)/g, ".0");
  value = value.replace(/'/g, '"');
  return value;
}

const parseAndTransform = () => {
  for (const key in tableData.value) {
    if (key.includes("取值公式")) {
      let valStr = tableData.value[key];
      // 如果值是字符串，先进行预处理
      if (typeof valStr === "string") {
        // 预处理字符串中的不规范浮点数表示
        valStr = preprocessValue(valStr);
      }
      const val = JSON.parse(valStr);
      resultData.value.参数名称.push(key.split("_")[0]); // 提取参数名称
      resultData.value.基本默认键值.push(val[0]);
      resultData.value.最小值.push(parseFloat(val[1]));
      resultData.value.最大值.push(parseFloat(val[2]));
      resultData.value.默认值.push(parseFloat(val[3]));
      resultData.value.分析步长值.push(parseFloat(val[4]));
    }
  }
  // 第二阶段：遍历剩余的字段，设置其他的数据
  for (const key in tableData.value) {
    if (!key.includes("取值公式")) {
      const index = resultData.value.参数名称.indexOf(key);
      if (index === -1) {
        resultData.value.参数名称.push(key);
        resultData.value.基本默认键值.push(tableData.value[key]);
      }
    }
  }
  transformedData();
};

const data = [];
const transformedData = async () => {
  tableData.value = [];
  const length = resultData.value.参数名称.length;
  for (let i = 0; i < length; i++) {
    const item = resultData.value;
    if (
      item.参数名称[i].includes("Cb变量取值公式") ||
      item.参数名称[i].includes("取值公式")
    ) {
      data.push({
        参数名称: item.参数名称[i],
        默认值: item.默认值[i],
        最小值: item.最小值[i],
        最大值: item.最大值[i],
        分析步长值: item.分析步长值[i],
        基本默认键值: item.基本默认键值[i],
      });
    } else if (item.参数名称[i].includes("自定义自变量约束条件")) {
      data.push({
        参数名称: item.参数名称[i] + "<0",
        默认值: null,
        最小值: null,
        最大值: null,
        分析步长值: null,
        基本默认键值: item.基本默认键值[i],
      });
    } else {
      data.push({
        参数名称: item.参数名称[i],
        默认值: null,
        最小值: null,
        最大值: null,
        分析步长值: null,
        基本默认键值: item.基本默认键值[i],
      });
    }
  }
  console.log(data);
  tableData1.value = [];
  tableData1.value = data
    .map((item) => ({
      ...item,
      editingColumn: null,
    }))
    .filter((item) => item.参数名称 !== "status" && item.参数名称 !== "lock");
  console.log("tableData1.value:", tableData1.value);
};

const currentEditRow = ref(null);

function editCell(row, columnProperty) {
  if (currentEditRow.value && currentEditRow.value !== row) {
    currentEditRow.value.editingColumn = null;
  }
  currentEditRow.value = row;
  row.editingColumn = columnProperty;
}

function saveEdit(row) {
  row.editingColumn = null;
  currentEditRow.value = null;
}

const dailogShow = ref(false);

function addRow() {
  dailogShow.value = true;
}

function handleFocus(index) {
  console.log(index);
}

const circuit_name = ref("");
const backendData = reactive({});

const transformData02 = (data) => {
  data.forEach((item) => {
    backendData.面板名称 = circuit_name.value;
    // 使用对象解构和数组.find 方法简化设置固定字段值的过程
    const fixedFields = [
      "CKH电压值",
      "CPU利用率百分比",
      "RA仿真Gn曲线电压均一性→（Gn peak max-Gn peak min）/Gn peak max",
      "RA仿真Gn曲线电压最小比例阈值→Gn peak/CKH",
      "RA补充仿真变量取值列表",
      "RA补充仿真变量识别关键字",
      "VSSG电压值",
      "Gn ripple峰值比例值→ripple peak/(CKH-VSSG)",
      "g曲线电压上升_下降时考虑的最大电压比例阈值",
      "g曲线电压上升_下降时考虑的最小电压比例阈值",
      "g曲线电压上升耗时",
      "g曲线电压下降耗时",
      "Gn曲线峰值最低阈值→Gn peak/CKH　",
      "Qn曲线Q1峰值最低阈值→Q1 peak/VGH",
      "Qn曲线Q2峰值最低阈值→Q2 peak/VGH",
      "Qn曲线ripple阈值→Q ripple/ (VGH-VGL)",
      "vgh仿真Gn曲线ripple阈值→ripple peak/(VGH-VSSG)",
      "vgh电压测评区间",
      "vgh电压识别关键字",
      "vgh高电压阈值",
      "vgl低电压阈值",
      "vth仿真Gn曲线ripple阈值→ripple peak/(VGH-VSSG)",
      "vth正偏电压末端折半尝试次数",
      "vth正偏电压测评区间",
      "vth电压识别关键字",
      "vth负偏电压末端折半尝试次数",
      "vth负偏电压测评区间",
      "单个变量维度划分网格数",
      "单轮演算仿真次数",
      "演算时间",
      "自定义自变量约束条件",
      "蒙特卡洛仿真设置参数",
      "vth正偏电压末端折半尝试次数",
      "vth负偏电压末端折半尝试次数",
      "vgh下限电压末端折半尝试次数",
    ];
    fixedFields.forEach((field) => {
      backendData[field] = tableData1.value.find(
        (it) => it.参数名称 === field
      )?.基本默认键值;
    });
    if (item.参数名称 === "自定义自变量约束条件<0") {
      backendData.自定义自变量约束条件 = item.基本默认键值;
    }
    if (item.参数名称.includes("变量取值公式")) {
      const key =
        item.参数名称.replace(/变量取值公式\d*/, "").trim() +
        "变量取值公式_最小值_最大值_默认值_分析步长值";
      backendData[
        key
      ] = `['${item.基本默认键值}', ${item.最小值}, ${item.最大值}, ${item.默认值}, ${item.分析步长值}]`;
    }
  });
};

const response1 = ref([]);
const uploadAlgorithm = async () => {
  const responser = await getAlgorithm(circuit_name.value);
  response1.value = responser;
  if (response1.value.lock === true) {
    const restrictedParams = [
      "单个变量维度划分网格数",
      "单轮演算仿真次数",
      "演算时间",
    ];
    const isRestricted = tableData1.value.some(
      (row) => !restrictedParams.includes(row.参数名称)
    );
    if (isRestricted) {
      const isConfirm = confirm(
        "该电路存在演算结果，若是继续上传将会根据修改的数据项，对相应的计算条目进行修改，是否确定继续修改？"
      );
      if (!isConfirm) {
        return;
      }
    }
  }
  transformData02(tableData1.value);
  try {
    const response1 = await addAlgorithmPre(backendData);
    if (
      response1.content &&
      (response1.content !== "" || response1.content != null)
    ) {
      const isConfirm = confirm(`${response1.content},请问是否继续`);
      if (isConfirm) {
        try {
          const response = await addAlgorithm(backendData);
          if (response.status == "success") {
            confirm("上传成功，请重新查询电路算法配置");
            ElMessage.success("上传成功");
            router.go(0);
          } else {
            confirm("上传失败，内容：", response.status);
            ElMessage.error("上传失败");
            router.go(0);
          }
        } catch (e) {
          console.error(e);
          ElMessage.error("上传失败，请联系维护人员");
        }
      } else {
        return;
      }
    } else {
      try {
        const response = await addAlgorithm(backendData);
        if (response.status == "success") {
          // confirm("上传成功，请重新查询电路算法配置");
          ElMessage.success("上传成功");
          // router.go(0);
        } else {
          confirm("上传失败，内容：", response.status);
          ElMessage.error("upload failed");
          router.go(0);
        }
      } catch (e) {
        console.error(e);
        ElMessage.error("上传失败，请联系维护人员");
      }
    }
  } catch (e) {
    const isConfirmed = confirm("上传失败，请联系维护人员");
    if (isConfirmed) {
      dailogShow.value = false;
      router.push({
        name: "电路配置",
        params: {
          circuitName: backendData.面板名称,
        },
      });
    } else {
      ElMessage.warning("操作取消");
    }
  }
};
const InsertFontsVue = defineAsyncComponent(() =>
  import("@/components/Inset/InsertFonts.vue")
);
const InsertFontsVueLoaded = ref(false);
onMounted(() => {
  getCircuit();
  if (InsertFontsVue) {
    InsertFontsVueLoaded.value = true;
  }
});

const getCircuit = async () => {
  try {
    const response = await circuitServer();
    results.value = response;
    result.value = results.value.name;
  } catch (error) {
    ElMessage.warning("获取电路失败");
    // console.error("出错了:", error);
  }
};
const isEdit = ref(true);
const selectOption = ref("");
const getConfig = async (circuitName) => {
  if (selectOption.value == "") {
    selectOption.value = isSelect.value;
    circuit_name.value = circuitName;
    console.log(circuitName);
    try {
      const response1 = await getAlgorithm(circuitName);
      if (response1.lock) {
        isEdit.value = false;
      }
      tableData.value = response1;
      console.log(tableData.value);
      parseAndTransform();
    } catch (e) {
      console.log("e:", e);
    }
  } else {
    confirm("当前页面已有数据，请先重置后在查询");
    router.go(0);
  }
};
</script>
<style scoped lang="scss">
.table-header {
  background-color: black;
}

.inputStyle {
  width: 850px;
}

table {
  div {
    cursor: pointer;
  }
}

header {
  padding: 20px;
  background-color: #f8f9fa;
}

main {
  margin-top: 20px;
}

footer {
  text-align: center;
  margin-top: 20px;
}
</style>
